package main

import (
	"ExcelExportGo/utils"
	"fmt"
	"os"
	"sync"
	"time"
)

const (
	FinishWords = "完毕"
	FailedWords = "失败"
)

func waitExit(runWords string, startT time.Time) {
	fmt.Printf("程序执行%s 耗时:%s 按 Enter 键退出...", runWords, time.Since(startT))
}

func main() {
	startT := time.Now()
	runWords := FinishWords

	// 启动参数
	// 配置表格路径, 服务器导出路径, 客户端导出路径, 多语言表xlsx名称, 多语言表导出路径
	args := os.Args
	if len(args) < 6 {
		println("参数格式:")
		println("\t配置表格路径, 服务器导出路径, 客户端导出路径, 多语言表xlsx名称, 多语言表导出路径")
		waitExit(runWords, startT)
		return
	}

	// 配置表格路径
	excelPath := args[1]
	serverOutPath := args[2]
	clientOutPath := args[3]
	languageFileName := args[4]
	languageOutPath := args[5]
	println(fmt.Sprintf("配置表格路径:%s, 服务器导出路径:%s, 客户端导出路径:%s, 多语言表xlsx名称:%s, 多语言表导出路径:%s", excelPath, serverOutPath, clientOutPath, languageFileName, languageOutPath))

	fileNum := 0
	files, err := utils.WalkFiles(excelPath, ".xlsx")
	if err != nil {
		runWords = FailedWords
		println(err.Error())
	} else {
		currNum := 0
		totalNum := len(files)
		err = utils.ClearDirectory(clientOutPath)
		if err != nil {
			println(fmt.Sprintf("清理客户端配置目录异常:%s", err.Error()))
			waitExit(runWords, startT)
			return
		}
		println(fmt.Sprintf("清理客户端配置目录:%s", clientOutPath))
		err = utils.ClearDirectory(serverOutPath)
		if err != nil {
			println(fmt.Sprintf("清理服务端配置目录异常:%s", err.Error()))
			waitExit(runWords, startT)
			return
		}
		println(fmt.Sprintf("清理服务端配置目录:%s", serverOutPath))

		var mutex sync.Mutex
		var waitGroup sync.WaitGroup
		for _, file := range files {
			go func() {
				waitGroup.Add(1)
				mutex.Lock()
				currNum++
				mutex.Unlock()
				fmt.Printf("读取文件(%d/%d):%s\n", currNum, totalNum, file)
				excelFile := utils.NewExcelFile(file)
				err = excelFile.Read()
				if err != nil {
					runWords = FailedWords
					println(err.Error())
					//break
				}
				err = excelFile.OutputFolder(serverOutPath, clientOutPath)
				if err != nil {
					runWords = FailedWords
					println(err.Error())
					//break
				}
				waitGroup.Done()
				mutex.Lock()
				fileNum++
				mutex.Unlock()
			}()
		}
		waitGroup.Wait()
	}
	println(fmt.Sprintf("=========================== 导出文件完成, 数量:%d ===========================", fileNum))
	waitExit(runWords, startT)
}
